package com.moonshine.parser.finder;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.moonshine.parser.models.AS3Signature;
import com.moonshine.parser.models.MethodSignature;
import com.moonshine.parser.models.VariableSignature;
import com.moonshine.utils.ListUtils;
import com.moonshine.utils.SignatureTools;

public class CompletionContext {

	private List<AS3Signature> completions = new ArrayList<AS3Signature>();

	public CompletionContext(List<AS3Signature> completions) {
		// TODO Auto-generated constructor stub
		this.completions = completions;
	}

	public CompletionContext() {
		// TODO Auto-generated constructor stub
	}

	public void output(String format, PrintStream out, Boolean pretty,
			Boolean shortClassNames) {
		// TODO Auto-generated method stub
		if (format.equals("xml")) {
			outputXML(out, pretty, shortClassNames);

		}

	}

	private void outputXML(PrintStream out, Boolean pretty,
			Boolean shortClassNames) {
		// TODO Auto-generated method stub

		out.append("<completions>");
		if (pretty)
			out.append("\n");
		Map<String, String> props = new HashMap<String, String>();
		MethodSignature method;
		List<String> params = new ArrayList<String>();
		for (AS3Signature sig : completions) {
			props.clear();
			props.put("name", formatClass(sig.name, shortClassNames));

			if (sig instanceof MethodSignature) {
				method = (MethodSignature) sig;
				props.put("type", "method");
				props.put("return", formatClass(method.returnType,
						shortClassNames));
				params.clear();
				for (VariableSignature param : method.paramaters) {
					params.add(param.name + ":"
							+ formatClass(param.declaredType, shortClassNames));
				}
				props.put("params", ListUtils.join(params, ","));

			} else {
				props.put("type",
						formatClass(((VariableSignature) sig).declaredType,
								shortClassNames));
			}
			if (pretty)
				out.append("\t");
			out.append("<n ");
			for (String key : props.keySet()) {
				out.append(String.format("%s=\"%s\" ", key, props.get(key)));
			}
			out.append("/>");
			if (pretty)
				out.append("\n");
		}

		out.append("</completions>");
		out.flush();
	}

	private String formatClass(String className, Boolean shortClassNames) {
		className = (shortClassNames) ? SignatureTools.getClassName(className)
				: className;

		if (className.indexOf("<") != -1) {

			className = className.replace("<", "");
			className = className.replace("<", "");
			className = "Vector:" + className;
		}
		return className;

	}
}
